<template>
  <el-card>
    <div slot="header">
      <span>{{ title }}</span>
    </div>
    <el-row type="flex" justify="center">
      <el-col :span="14">
        <el-form
          class="table_form_wrap"
          ref="recordForm"
          :model="recordForm"
          :rules="formValidate"
          label-width="140px"
        >
          <el-form-item label="供应商代码" prop="supplierCode">
            <el-input
              readonly
              v-model.trim="recordForm.supplierCode"
              placeholder="请选择供应商代码"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="showSupplierDialog"
              ></el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="供应商名称" prop="supplierName">
            <el-input
              disabled
              v-model.trim="recordForm.supplierName"
              :placeholder="supplierPlaceholder"
            />
          </el-form-item>
          <el-form-item label="采购归属" prop="belongDepartmentName">
            <el-input
              disabled
              v-model.trim="recordForm.belongDepartmentName"
              :placeholder="supplierPlaceholder"
            />
          </el-form-item>
          <el-form-item label="管理区域" prop="belongAreaName">
            <el-input
              disabled
              v-model.trim="recordForm.belongAreaName"
              :placeholder="supplierPlaceholder"
            />
          </el-form-item>
          <el-form-item label="来访人员" prop="visitPerson">
            <el-select
              v-model.trim="recordForm.visitPerson"
              value-key="personName"
              placeholder="请选择来访人员"
              filterable
              @change="handleVisitPersonSelect"
            >
              <el-option
                v-for="item in visitPersonOptions"
                :key="item.id"
                :label="item.personName"
                :value="item.id"
              />
            </el-select>
            <!-- <el-select
              v-model="recordForm.visitPerson"
              filterable
              :filter-method="(query) => handleFilterOptions(query, optionsObj)"
              placeholder="请选择来访人员"
              collapse-tags
              clearable
            >
              <el-option
                v-for="item in optionsObj.options"
                :key="item.id"
                :label="item.personName"
                :value="item.id"
              />
            </el-select> -->
          </el-form-item>
          <el-form-item label="来访人员联系方式" prop="visitPersonPhone">
            <el-input
              disabled
              v-model.trim="recordForm.visitPersonPhone"
              placeholder="输入来访人员联系方式"
            />
          </el-form-item>
          <el-form-item label="来访时间" prop="visitTime">
            <el-date-picker
              v-model="recordForm.visitTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择来访时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="接待人" prop="unawares">
            <el-input
              readonly
              v-model="recordForm.unawares"
              placeholder="请选择接待人"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="showHrUserDialog"
              ></el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="业务对接人" prop="businessCounterpart">
            <el-input
              disabled
              v-model.trim="recordForm.businessCounterpart"
              :placeholder="supplierPlaceholder"
            />
          </el-form-item>
          <el-form-item label="来访目的" prop="visitPurpose">
            <el-input
              type="textarea"
              v-model.trim="recordForm.visitPurpose"
              placeholder="请输入来访目的"
              show-word-limit
              :minlength="3"
              :maxlength="500"
            />
          </el-form-item>
          <el-form-item label="来访结果" prop="visitResult">
            <el-input
              type="textarea"
              v-model.trim="recordForm.visitResult"
              placeholder="请输入来访结果"
              show-word-limit
              :minlength="3"
              :maxlength="3000"
            />
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center">
      <el-button type="primary" @click="handleSubmit">提交</el-button>
      <el-button type="primary" @click="handleStash">暂存</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </el-row>
    <SelectSupplierDialog
      :supplierVisible.sync="dialogVisible"
      @handle-select="handleGetSupplierInfo"
    />
    <HrUserDialog
      :isVisit="true"
      :hrUserVisible.sync="hrDialogVisible"
      :personList="recordForm.unawaresNo.split(',').filter(item => item != '')"
      @handle-select="handleGetUserList"
    />
  </el-card>
</template>
<script>
import SelectSupplierDialog from '@/pages/supplier/components/SelectSupplierDialog.vue'
import HrUserDialog from '@/pages/supplier/components/SelectHrUser.vue'
import {
  queryRecordDetailService,
  querySupplierPersonInfoService,
  addRecordService,
  getRecordBillByIdService,
  stashVisitRecordService,
} from '@api/supplier/returnVisteManage';
import { isResponseSuccess } from '@/pages/supplier/utils/bizUtils';

export default {
  components: {
    SelectSupplierDialog,
    HrUserDialog
  },
  data () {
    return {
      id: null,
      visitId: null,
      processId: null,
      submitLoading: false,
      dialogVisible: false,
      hrDialogVisible: false,
      supplierPlaceholder: '根据供应商代码搜索出结果后，自动写入，不可修改',
      recordForm: {
        supplierId: '', // 供应商ID
        supplierCode: '', // 供应商代码
        supplierName: '', // 供应商名称
        belongDepartmentName: '', // 采购归属
        belongArea: '', // 供应商管理区域code
        belongAreaName: '', // 供应商管理区域
        visitPerson: '', // 来访人员
        visitPersonName: '', // 来访人员
        visitPersonPhone: '', // 来访人员联系方式
        visitTime: '', // 来访时间
        unawares: '', // 创建人/接待人
        unawaresNo: '', // 创建人id
        businessCounterpart: '', // 业务对接人
        visitPurpose: '', // 来访目的
        visitResult: '', // 来访结果
      },
      formValidate: {
        supplierCode: [
          { required: true, message: '供应商代码不能为空', trigger: 'change' }
        ],
        supplierName: [
          { required: true, message: '供应商名称不能为空', trigger: 'change' }
        ],
        belongDepartmentName: [
          { required: true, message: '采购归属不能为空', trigger: 'change' }
        ],
        belongAreaName: [
          { required: true, message: '管理区域不能为空', trigger: 'change' }
        ],
        visitPerson: [
          { required: true, message: '来访人员不能为空', trigger: 'change' }
        ],
        visitPersonPhone: [
          { required: true, message: '来访人员联系方式不能为空', trigger: 'change' }
        ],
        visitTime: [
          { required: true, message: '来访时间不能为空', trigger: 'change' }
        ],
        unawares: [
          { required: true, message: '接待人不能为空', trigger: 'change' }
        ],
        /* businessCounterpart: [
          { required: true, message: '业务对接人不能为空', trigger: 'change' }
        ], */
        visitPurpose: [{ required: true, message: '来访目的不能为空', trigger: 'blur' }],
        visitResult: [
          { required: true, message: '来访结果不能为空', trigger: 'blur' }
        ]
      },
      optionsObj: {
        options: [], // 可视来访人员集合
        allOptions: [], // 来访人员全集
      },
      visitPersonOptions: []
    }
  },
  computed: {
    title () {
      return this.id ? '修改供应商来访记录' : '新建供应商来访记录';
    },
    isBill () {
      return typeof this.$route.query.processId !== 'undefined'
    }
  },
  created () {
    const { id, processId, visitId } = this.$route.query;
    this.id = id;
    this.visitId = visitId
    if (this.isBill) {
      this.processId = processId;
      this.getBillDetailById(id)
    } else if (id) {
      this.getDetailData(id)
    }
  },
  methods: {
    // 显示出差人员
    showHrUserDialog () {
      this.hrDialogVisible = true;
    },
    // 获取已选出差人员集合
    handleGetUserList ({ row, type }) {
      let jobNumberList = [];
      let userNameList = [];
      jobNumberList = this.recordForm.unawaresNo.split(',').filter(item => item != '')
      userNameList = this.recordForm.unawares.split(',').filter(item => item != '')
      if (type == 'select') {
        const { jobNumber, userName } = row;
        if (this.recordForm.unawaresNo) {
          if (!jobNumberList.includes(jobNumber)) {
            jobNumberList.push(jobNumber)
            userNameList.push(userName)
          }
        } else {
          jobNumberList.push(jobNumber)
          userNameList.push(userName)
        }
      } else {
        jobNumberList = jobNumberList.filter(item => item !== row.jobNumber)
        userNameList = userNameList.filter(item => item !== row.userName)
      }
      this.initPersonListStr(jobNumberList, userNameList)
    },
    // 格式化出差人员
    initPersonListStr (jobNumberList, userNameList) {
      this.$set(this.recordForm, 'unawaresNo', jobNumberList.join(','));
      this.$set(this.recordForm, 'unawares', userNameList.join(','));
    },
    // 显示供应商弹框
    showSupplierDialog () {
      this.dialogVisible = true;
    },
    // 关闭弹框
    handleColseSupplierDialog () {
      this.dialogVisible = false;
    },
    // 提交
    handleSubmit () {
      const { visitPurpose, visitResult } = this.recordForm;
      if (visitPurpose.length < 3) {
        return this.$message.warning('来访目的长度不能小于3')
      }
      if (visitResult.length < 3) {
        return this.$message.warning('来访结果长度不能小于3')
      }
      this.$refs['recordForm'].validate((valid) => {
        if (valid) {
          if (this.visitPersonOptions.length) {
            const person = this.visitPersonOptions.find(item => item.id == this.recordForm.visitPerson)
            if (person) {
              this.recordForm.visitPersonName = person.personName;
            }
          }
          const params = { ...this.recordForm }
          if (this.id && (!this.isBill || (this.isBill && this.visitId))) {
            params.visitId = this.id
          }
          if (!this.isBill) {
            delete params.id
          }

          addRecordService(params).then((res) => {
            if (isResponseSuccess(res)) {
              this.$message.success(res.message);
              this.handleCancel()
            }
          })
        }
      })
    },
    // 暂存
    handleStash () {
      const params = { ...this.recordForm, processBillId: this.processId || 0 }
      if (this.visitPersonOptions.length) {
        params.visitPersonName = this.visitPersonOptions.find(item => item.id == this.recordForm.visitPerson).personName;
      }
      if (this.id && (!this.isBill || (this.isBill && this.visitId))) {
        params.visitId = this.id
      }
      if (!this.isBill) {
        delete params.id
      }
      stashVisitRecordService(params).then(res => {
        if (isResponseSuccess(res)) {
          this.$message.success('暂存成功');
          this.handleCancel()
        }
      })
    },
    // 获取详情
    getBillDetailById (id) {
      getRecordBillByIdService({ id }).then((res) => {
        if (isResponseSuccess(res)) {
          this.recordForm = res.result;
          this.getSupplierPersonData()
        }
      })
    },
    // 获取供应商信息
    handleGetSupplierInfo (row) {
      const {
        supplierCode, // 供应商编码
        supplierName, // 供应商名称
        supplierId, // 供应商id
        belongDepartment, // 供应商归属中心
        belongDepartmentName, // 供应商归属中心
        managementAreaName, // 供应商管理区域
        managementAreaId, // 供应商管理区域ID
        businessContact, // 公司业务对接人ID
        businessContactName // 公司业务对接人
      } = row;
      this.recordForm = {
        ...this.recordForm,
        supplierCode,
        supplierName,
        supplierId,
        belongDepartment,
        belongDepartmentName,
        belongArea: managementAreaId,
        belongAreaName: managementAreaName,
        managementAreaName,
        businessContact,
        businessCounterpart: businessContactName,
        // businessContactName,
        visitPerson: '',
        visitPersonPhone: '',
      }
      this.getSupplierPersonData()
    },
    // 获取详情
    getDetailData () {
      queryRecordDetailService({ id: this.id }).then((res) => {
        if (isResponseSuccess(res)) {
          const { result } = res;
          this.recordForm = result;
          this.getSupplierPersonData()
        }
      })
    },
    // 获取来访人员信息
    getSupplierPersonData () {
      const params = {
        supplierId: this.recordForm.supplierId
      }
      querySupplierPersonInfoService(params).then((res) => {
        if (isResponseSuccess(res)) {
          const { result } = res;
          // this.optionsObj.allOptions = result;
          this.visitPersonOptions = result;
        }
      })
    },
    handleFilterOptions (query = '', obj) {
      let arr = obj.allOptions.filter(item => {
        return item.label.includes(query);
      });
      if (arr.length > 30) {
        obj.options = arr.slice(0, 30);
      } else {
        obj.options = arr;
      }
    },
    // 联系电话赋值
    handleVisitPersonSelect (val) {
      console.log(val)
      this.recordForm.visitPersonPhone = this.visitPersonOptions.find(item => item.id == val).contactPhone
    },
    // 取消
    handleCancel () {
      this.$router.go(-1);
    },
  }
};
</script>
